<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button id="btn1">建立连接</button>
  <button id="btn2">发送消息</button>
  <button id="btn3">断开消息</button>
  <script>
    const btn1 = document.querySelector('#btn1')
    const btn2 = document.querySelector('#btn2')
    const btn3 = document.querySelector('#btn3')
    let ws 
    // 点击按钮 建立连接
    btn1.addEventListener('click', () => {
       ws = new WebSocket('wss://javascript.info/article/websocket/demo/hello')
      //  监听是否建立连接成功
       ws.onopen = () => {
        console.log('连接成功')
       }
       // 结束服务器回复的消息
       ws.onmessage = (e) => {
        console.log(e.data)
       }
      //  监听端开连接
      ws.onclose = () => {
        console.log('连接已关闭')
      }
    })
    btn2.addEventListener('click', () => {
      // 发送消息给服务器
      ws.send('你好啊aaa')
    })

    btn3.addEventListener('click', () => {
      // 断开连接
      ws.close()
    })
  </script>
</body>
</html>